<script lang="ts" setup>
import { format } from 'date-fns';
import { storeToRefs } from 'pinia';
import { computed, ref } from 'vue';
import { usePopupStore } from '@/store/popup';
import { getDefaultAfterDate, getDefaultBeforeDate } from '@/utils/date';
import { useLocale } from "@/locale/locale";

const props = defineProps<{
  startDate: string;
  endDate: string;
}>();

const { t } = useLocale();
const popupStore = usePopupStore();
const { datePickerRef } = storeToRefs(popupStore);

const nowDate = ref(format(new Date(), 'yyyy-MM-dd'));

const currentDate = ref({
  before: getDefaultBeforeDate(),
  after: getDefaultAfterDate()
});

popupStore.onOpened('DATE', () => {
  currentDate.value.before = props.startDate;
  currentDate.value.after = props.endDate;
});

function handleCalendarChange(value: any) {
  const { before, after } = value.range;
  currentDate.value.before = before;
  currentDate.value.after = after;
}

const currentConfirmText = computed(() => {
  if (!currentDate.value.before) {
    return t('PleaseSelectDate');
  }

  if (!currentDate.value.after) {
    return t('LCKey_noCheckOutDate');
  }

  return t('WellChosen');
});

const isDisabled = computed(() => {
  return !currentDate.value.before || !currentDate.value.after;
});

defineEmits<{ update: [startDate: string, endDate: string] }>();
</script>

<template>
  <apt-popup
    ref="datePickerRef"
    :confirm-text="currentConfirmText"
    :disabled="isDisabled"
    :title="t('SelectDate')"
    @close="popupStore.closeDatePicker"
    @confirm="$emit('update', currentDate.before, currentDate.after)"
  >
    <view class="apt-date-picker">
      <uni-calendar
        :date="currentDate"
        :show-month="false"
        :start-date="nowDate"
        range
        @change="handleCalendarChange"
      />
    </view>
  </apt-popup>
</template>
